package com.pirestupppai.imagetool.filtertool;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pirestupppai.R;

import java.util.List;

/**
 * 滤镜选择Adapter
 */

public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.FilterViewHolder> {
    private int lastPosition = 0;
    private FilterSelectCallBack mFilterSelectCallBack;
    private List<FilterItem> mFilterItems;
    private Context mContext;
    private LayoutInflater mInflater;

    public FilterAdapter(List<FilterItem> filterItems, Context context, FilterSelectCallBack filterSelectCallBack) {
        this.mFilterItems = filterItems;
        this.mContext = context;
        this.mFilterSelectCallBack = filterSelectCallBack;
        this.mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public FilterAdapter.FilterViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
        View itemView = mInflater.inflate(R.layout.item_select_filter, viewGroup, false);
        return new FilterViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(FilterViewHolder holder, final int position) {

        holder.setData(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lastPosition != position) {
                    mFilterSelectCallBack.onSelectClick(mFilterItems.get(position).filter);
                    lastPosition = position;
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mFilterItems.size();
    }

    public class FilterViewHolder extends RecyclerView.ViewHolder {
        public ImageView filterImg;
        public RelativeLayout filterSelectBackground;
        public TextView filterNameTv;

        public FilterViewHolder(View v) {
            super(v);
            this.filterImg = (ImageView) v.findViewById(R.id.filter_select_img);
            this.filterSelectBackground = (RelativeLayout) v.findViewById(R.id.filter_select_background);
            this.filterNameTv = (TextView) v.findViewById(R.id.filter_name_tv);
        }

        public void setData(int position) {
            final FilterItem filterItem = mFilterItems.get(position);
            filterImg.setImageBitmap(filterItem.image);
            if (position == 0) {
                filterNameTv.setVisibility(View.VISIBLE);
            } else {
                filterNameTv.setVisibility(View.INVISIBLE);
            }

            if (lastPosition == position) {
                filterSelectBackground.setVisibility(View.VISIBLE);
            } else {
                filterSelectBackground.setVisibility(View.INVISIBLE);
            }
        }
    }
}
